<template>
  <div>
    <!-- 表格 -->
    <el-table
      :data="tableData"
      style="width: 100%, min-height:600px"
      :row-class-name="tableRowClassName"
      empty-text="无发布版本"
      v-loading="loading"
    >
      <el-table-column type="index" width="80" label="序号" />
      <el-table-column prop="name" label="名称" width="180" />
      <el-table-column prop="versionName" label="版本名" width="180" />
      <el-table-column prop="versionCode" label="版本号" width="100" />
      <el-table-column prop="status" label="状态" width="100" />
      <el-table-column prop="createTime" label="创建时间" width="150"/>
      <el-table-column prop="desc" label="版本说明" width="380" />
      <el-table-column align="right">
        <template #header>
          <el-input
            v-model="search"
            size="small"
            placeholder="检索"
            style="width: 200px; margin-right: 10px"
            :prefix-icon="Search"
          />
          <el-button type="primary" :icon="Plus" @click="toVersion" circle></el-button>
          <el-button type="primary" :icon="Refresh" @click="refresh" circle />
        </template>
        <template #default="scope">
          <el-button size="small" @click="openInfo(scope.row)"> 详情 </el-button>
          <el-button size="small" @click="downloadApk(scope.row)"> 下载 </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 详情页 -->
    <el-drawer v-model="drawer" title="版本详情" :destroy-on-close="true">
      <VersionInfo :version-id="versionId" />
    </el-drawer>
    <!-- 分页 -->
    <div style="margin-top: 15px; float: right">
      <el-pagination 
      background layout="prev, pager, next" 
      :page-count="pageTotal"
      @current-change="getTable" />
    </div>
    <el-dialog v-model="versionVisible" title="版本发布" destroy-on-close>
      <VersionAdd />
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, onBeforeMount, provide } from 'vue'
import { VersionPageApi, ApkDownloadApi } from '@/api'
import type { VersionPageReq, VersionListResult } from '@/api/types'
import { useCounterStore } from '@/stores/manage'
import VersionInfo from '@/views/version-info.vue'
import VersionAdd from '@/views/version-add.vue'
import { ElMessage } from 'element-plus'
import { Plus, Refresh, Search } from '@element-plus/icons-vue'

const manager = useCounterStore()

// 是否显示详情页
const drawer = ref(false)
const search = ref('')
const tableData = ref<VersionListResult[]>()
const pageTotal = ref(1)
const currentPage = ref(1)
const loading = ref(false)
const versionId = ref('')
const total = ref(1)

// 分页检索
const pageQuery: VersionPageReq = {
  pageNum: 1,
  pageSize: 10,
  query: search.value,
  appId: manager.getAppId()
}

// 版本列表
onBeforeMount(() => {
  getTable(1)
})

const refresh = () => {
  getTable(1)
}

const getTable = (pageNum: number) => {
  loading.value = true
  pageQuery.pageNum = pageNum
  VersionPageApi(pageQuery)
    .then((res) => {
      const data = res.data
      if (data.code != 200) {
        ElMessage.error(data.msg)
      } else {
        // 分页数据
        const pageData = data.data
        tableData.value = pageData.data
        pageTotal.value = pageData.totalPages
        currentPage.value = pageData.currentPage
        total.value = pageData.totalCount

      }
    })
    .catch((error) => {
      console.log(error)
    })
    .finally(() => {
      loading.value = false
    })
}

const downloadApk = (versionData: VersionListResult) => {
  const versionId = versionData.versionId
  ApkDownloadApi(versionId).then((response) => {
    console.log(response)
    if (response.status != 200) {
      ElMessage.error("apk文件下载失败")
      return
    }
    // 创建一个临时的 Blob 对象
    const blob = new Blob([response.data], { type: response.headers['content-type'] })

    // 生成临时的下载链接
    const downloadLink = URL.createObjectURL(blob)

    // 创建一个隐藏的 <a> 元素
    const a = document.createElement('a')
    a.style.display = 'none'
    a.href = downloadLink
    a.download = versionData.versionCode + '.apk' // 设置下载的文件名
    document.body.appendChild(a)

    // 模拟点击下载链接
    a.click()

    // 清理临时的下载链接和 <a> 元素
    URL.revokeObjectURL(downloadLink)
    document.body.removeChild(a)
  })
}

// 每行状态不一样，背景显示不一样
const tableRowClassName = ({ row, rowIndex }: { row: VersionListResult; rowIndex: number }) => {
  if (row.status === '待发布') {
    return 'warning-row'
  } else if (row.status === '已发布') {
    return 'success-row'
  }
  return ''
}

const openInfo = (row: VersionListResult) => {
  versionId.value = row.versionId
  drawer.value = true
}

// 暴露方法给父页面调用
defineExpose({ refresh })

// 控制版本添加页面
const versionVisible = ref(false)
// 打开版本添加页面
const toVersion = () => {
  versionVisible.value = true
}
// 关闭版本添加页面
const closeVersion = () => {
  versionVisible.value = false
}
provide('closeVersion', closeVersion)
</script>

<style>
.el-table .warning-row {
  --el-table-tr-bg-color: var(--el-color-warning-light-9);
}
.el-table .success-row {
  --el-table-tr-bg-color: var(--el-color-success-light-9);
}
</style>
